package yxgf.oem.oemquotemgt.plugin.form;

import com.alibaba.nacos.common.utils.StringUtils;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.entity.BadgeInfo;
import kd.bos.entity.datamodel.IEntryOperate;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.AfterF7SelectEvent;
import kd.bos.form.field.events.AfterF7SelectListener;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListShowParameter;
import kd.bos.openapi.common.result.CustomApiResult;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.DispatchServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.fi.bcm.business.convert.query.BaseData;
import net.bytebuddy.dynamic.DynamicType;
import yxgf.oem.oemquotemgt.commons.constants.MarketBillIdConstant;
import yxgf.oem.oemquotemgt.commons.constants.NumConstant;
import yxgf.oem.oemquotemgt.commons.constants.MarketBillMsgConstant;
import yxgf.oem.oemquotemgt.commons.dto.*;
import yxgf.oem.oemquotemgt.commons.enums.CusTypeEnum;
import yxgf.oem.oemquotemgt.commons.enums.CustomerTypeEnum;
import yxgf.oem.oemquotemgt.commons.enums.StockTypeEnum;
import yxgf.oem.oemquotemgt.mservice.service.impl.MarketBillServiceImpl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description： 营销配方插件
 * @version: v1.0
 * @author: Junit
 * @date: 2025/5/12
 */
public class MarketBillFormPlugIn extends AbstractFormPlugin implements BeforeF7SelectListener, AfterF7SelectListener {
    private volatile int times = 0;

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        setDefStockType();
    }


    @Override
    public void registerListener(EventObject e) {
        this.addItemClickListeners("advcontoolbarap", "yxgf_advcontoolbarap_nut");
        super.registerListener(e);

        BasedataEdit be = this.getControl(MarketBillIdConstant.MAT_FORMULA_CODE);
        be.addBeforeF7SelectListener(this);
    }

    //
    @Override
    public void itemClick(ItemClickEvent evt) {
        String itemKey = evt.getItemKey();
        if (StringUtils.equalsIgnoreCase(itemKey, MarketBillIdConstant.OPP_COMPUTE_PRICE)) {
            calculateProPrice();
            getView().showSuccessNotification(MarketBillMsgConstant.COMPUTE_FINISHED);
        }
        if (StringUtils.equalsIgnoreCase(itemKey, MarketBillIdConstant.OPP_COMPUTE_NUT_ITEM)) {
            selectNutItem();
            getView().showSuccessNotification(MarketBillMsgConstant.COMPUTE_FINISHED);
        }
        super.itemClick(evt);
    }


    @Override
    public void afterF7Select(AfterF7SelectEvent afterF7SelectEvent) {
        // 获取选中行
        ListSelectedRow selectRowList = afterF7SelectEvent.getListSelectedRow();
        ListSelectedRowCollection selectedRows = afterF7SelectEvent.getListSelectedRowCollection();
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent beforeF7SelectEvent) {
//        String fieldKey = beforeF7SelectEvent.getProperty().getName();
//        if (StringUtils.equals(fieldKey, "yxgf_material_code")) {
//            int row = beforeF7SelectEvent.getRow();
//            DynamicObject obj = (DynamicObject) this.getModel().getValue("yxgf_material_code", row);
//            if (obj != null) {
//                // 获取当前行的信息基础资料的id,生成过滤条件对象
//                Long id = obj.getLong("id");
//                String number = String.valueOf(obj.getLong("number"));
//
//                QFilter qfilter = new QFilter("number", QCP.not_equals, number);
//                // 设置F7列表数据过滤条件
//                ListShowParameter showParameter = (ListShowParameter) beforeF7SelectEvent.getFormShowParameter();
//                showParameter.getListFilterParameter().getQFilters().add(qfilter);
//            }
//        }
    }


    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        String fieldKey = e.getProperty().getName();

        switch (fieldKey) {
            case MarketBillIdConstant.MAT_FORMULA_CODE:
                DynamicObject formulaObj = (DynamicObject) e.getChangeSet()[0].getNewValue();
                formulaDetailListen(formulaObj.getString(MarketBillIdConstant.BILL_NUM));
                break;
            case MarketBillIdConstant.MAT_DETAIL_CODE:
                DynamicObject detailObj = (DynamicObject) e.getChangeSet()[0].getNewValue();
                formulaPriceDetailListen(detailObj.getString(MarketBillIdConstant.BILL_NUM),true);
                break;
            case MarketBillIdConstant.BUS_DATE:
                setDefStockType();
                break;
            case MarketBillIdConstant.PRODUCT_DETAIL_STD:
                DynamicObject proObj = (DynamicObject) e.getChangeSet()[0].getNewValue();
                buildProDetail(proObj.getString(MarketBillIdConstant.BILL_NUM));
                break;
            case MarketBillIdConstant.OPP_FORMULA_IMPORT:
                DynamicObject forVersionObj = (DynamicObject) e.getChangeSet()[0].getNewValue();
                importFormulaVersion(forVersionObj);
                break;
            case MarketBillIdConstant.OPP_FORMULA_INST:
                DynamicObject instObj = (DynamicObject) e.getChangeSet()[0].getNewValue();
                importFormulaInst(instObj);
                break;
            case MarketBillIdConstant.MARKET_CUS_TYPE:
                setDefCusType();
                break;
            default:
                break;
        }
    }

    /**
     * 监听配方时，
     * -监听是产品存在性
     * -监听配方存在性
     * -监听价格存在性
     *
     * @param materialCode
     */
    private void formulaDetailListen(String materialCode) {
        // 1、判断产品是否存在
        if (!isExistPro(MarketBillIdConstant.PRODUCT_DETAIL, MarketBillIdConstant.MAT_CODE, false)) {
            this.getView().showMessage(MarketBillMsgConstant.SELECT_PRODUCT);
            this.getModel().deleteEntryRow("yxgf_ent_product_formula", NumConstant.DEF_ROW);
            this.getModel().createNewEntryRow("yxgf_ent_product_formula");
            return;
        }
        // 2、记录配方分录
        int existForData[] = existFormulaRow(materialCode);
        if (existForData[0] == -1) {
            DynamicObjectCollection collection = getModel().getEntryEntity(MarketBillIdConstant.ENTITY_FORMULA);
            // 获取产品分录行
            int proRow = getProRow(MarketBillIdConstant.PRODUCT_DETAIL);
            // 获取配方分录行
            int subRow = getProRow(MarketBillIdConstant.ENTITY_FORMULA);
            addFormulaRow(proRow, subRow, collection, materialCode);
        }
        // 3、判断在价格明细中是否存在配方价
        int existForPrice[] = existForPriceRow(materialCode);
        DynamicObjectCollection collection = getModel().getEntryEntity(MarketBillIdConstant.MAT_PRICE_DETAIL);
        if (existForPrice[0] == -1) {
            // 获取配方分录行
            int row = (existForPrice[1] == 0) ? 0 : (existForPrice[1] - 1);
            this.getModel().createNewEntryRow(MarketBillIdConstant.MAT_PRICE_DETAIL);
            genPriceDetail(row, materialCode);
        }
    }


    /**
     * 获取产品选中的行号
     *
     * @return
     */
    private int getProRow(String tag) {
        // 获取产产品单据体控件
        EntryGrid entryGrid = this.getControl(tag);
        // 获取选中行，数组为行号，从0开始int[]
        int selectRows[] = entryGrid.getSelectRows();
        if (selectRows.length > 0) {
            return selectRows[0];
        }
        return 0;
    }


    /**
     * 监听价格，加入价格明细：
     * -监听价格时，判断价格存在性
     *
     * @param materialCode
     */
    private void formulaPriceDetailListen(String materialCode,Boolean selfListen) {
        // 监听自己操作
       if(selfListen){
           // 判断在价格明细中是否存在配方价格
           int exData[] = existForPriceRow(materialCode);
           // 获取配方分录行
           int subRow = getProRow(MarketBillIdConstant.MAT_PRICE_DETAIL);
           if (exData[0] == -1) {
               genPriceDetail(subRow, materialCode);
           }
       }
    }

    /**
     * 是否存在配方价格分录
     *
     * @return
     */
    private int[] existForPriceRow(String materialCode) {
        int[] arr = {-1, 0, 0};
        int defRow = 0;
        DynamicObjectCollection collection = getModel().getEntryEntity(MarketBillIdConstant.MAT_PRICE_DETAIL);
        if (collection != null && collection.size() > 1) {
            arr[1] = collection.size();
            for (int i = 0; i < collection.size() - 1; i++) {
                DynamicObject dynObj = (DynamicObject) this.getModel().getValue("yxgf_material_no", i);
                if (dynObj != null) {
                    String number = dynObj.getString("number");
                    if (StringUtils.equals(materialCode, number)) {
                        arr[2] = i;
                        defRow += 1;
                    }
                    if (defRow > 1) {
                        arr[0] = 1;
                        return arr;
                    }
                }
            }
        }
        return arr;
    }

    /**
     * 配方是否存在分录
     * 参数1：-1：不存在，1-存在同数据；参数2：总长度,；参数3：位置
     *
     * @return
     */
    private int[] existFormulaRow(String materialCode) {
        int[] arr = {-1, 0, 0};
        int defRow = 0;
        DynamicObjectCollection collection = getModel().getEntryEntity("yxgf_ent_product_formula");
        if (collection != null && collection.size() > 0) {
            arr[1] = collection.size();
            for (int i = 0; i < collection.size() - 1; i++) {
                DynamicObject dynObj = (DynamicObject) this.getModel().getValue("yxgf_material_code", i);
                if (StringUtils.equals(materialCode, dynObj.getString("number"))) {
                    arr[2] = i;
                    defRow += 1;
                }
                if (defRow > 1) {
                    arr[0] = 1;
                    return arr;
                }
            }
        }
        return arr;
    }

    /**
     * 设置价格行
     *
     * @param subRow
     * @param list
     * @param materialCode
     */
    private void addFormulaRow(int parRow, int subRow, DynamicObjectCollection list, String materialCode) {
        QFilter qfilter = new QFilter("number", QCP.equals, materialCode);
        DynamicObject dynObj = QueryServiceHelper.queryOne("bd_material", "id", qfilter.toArray());

        List<MarketFormulaDto> materialList = new ArrayList<>();
        MarketFormulaDto dto = new MarketFormulaDto();
        dto.setMatId((Long) dynObj.get("id"));
        dto.setMatCode(materialCode);
        materialList.add(dto);
        createSubEntity(parRow, subRow, materialList);
    }


    /**
     * 构建价格明细
     *
     * @param index        分录行
     * @param materialCode
     */
    private void genPriceDetail(int index, String materialCode) {
        DynamicObject orgObj = (DynamicObject) this.getModel().getValue("org");
        if (orgObj != null) {
            String orgCode = (String) orgObj.get("number");
            String stockType = (String) getModel().getValue("yxgf_kcjlx");
            Object cusType = this.getModel().getValue("yxgf_cus_type");

            // 价格处理
            CustomApiResult<PriceDto> apiResult = DispatchServiceHelper.invokeService("yxgf.oem.oemquotemgt.mservice.factory", "llj-quotemgt", "IPriceService", "getPriceList", orgCode, materialCode, stockType, "");
            PriceDto res = apiResult.getData();

            // 创建分录
            if(index == -1){
                this.getModel().createNewEntryRow(MarketBillIdConstant.MAT_PRICE_DETAIL);
            }

            // 获取原料
            QFilter qfilter = new QFilter("number", QCP.equals, materialCode);
            DynamicObject dynObj = QueryServiceHelper.queryOne("bd_material", "id", qfilter.toArray());
            long id = (long) dynObj.get("id");
            // 绑定原料
            this.getModel().setValue("yxgf_material_no", id, index);
            this.getModel().setValue("yxgf_mark_price", res.getForPrice(), index);
            this.getModel().setValue("yxgf_stock_price", res.getStockPrice(), index);

            /**
             * 客户类型
             * 1、商机客户-获取crm客户编码
             */
            BigDecimal comPrice = BigDecimal.ZERO;
            if (StringUtils.equals(CustomerTypeEnum.CUS_CRM.getCode(), cusType.toString())) {
                DynamicObject crmObj = (DynamicObject) this.getModel().getValue("yxgf_crm_customer");
                String crmCode = (String) crmObj.get("number");
                comPrice = DispatchServiceHelper.invokeService("yxgf.oem.oemquotemgt.mservice.factory", "llj-quotemgt", "IPriceService", "getCompPrice", crmCode, materialCode);
            }
            this.getModel().setValue("yxgf_comp_price", comPrice, index);
            // 友商信息
            this.getModel().setValue("yxgf_cwyljj_text", res.getFinancePrice(), index);
        } else {
            this.getView().showMessage(MarketBillMsgConstant.SELECT_STOCK_ORG);
        }
    }

    /**
     * 设置库存类型
     */
    private void setDefStockType() {
        Date busDat = (Date) this.getModel().getValue(MarketBillIdConstant.BUS_DATE);
        SimpleDateFormat dayFormat = new SimpleDateFormat("d");
        if (Integer.parseInt(dayFormat.format(busDat)) > NumConstant.DEF_DAYS) {
            getModel().setValue(MarketBillIdConstant.STOCK_TYPE, StockTypeEnum.MARKET_SEC_HALF_MONTH.getCode());
        } else {
            getModel().setValue(MarketBillIdConstant.STOCK_TYPE, StockTypeEnum.MARKET_FIRST_HALF_MONTH.getCode());
        }
    }

    /**
     * 校验组织
     *
     * @return
     */
    public boolean verifyOrg() {
        DynamicObject orgObj = (DynamicObject) this.getModel().getValue("org");
        if (orgObj != null && !StringUtils.isEmpty(orgObj.get("number").toString())) {
            return true;
        }
        return false;
    }


    /**
     * 校验方式
     * 1、校验单据体是否有数据
     * 2、是否选中分录
     *
     * @return
     */
    private boolean isExistPro(String billId, String verCol, boolean firstRow) {
        DynamicObjectCollection collection = getModel().getEntryEntity(billId);
        if (collection != null && collection.size() > 0) {
            for (int i = 0; i < collection.size(); i++) {
                Object dynObj = this.getModel().getValue(verCol, i);
                if ((dynObj != null) && !StringUtils.isEmpty(dynObj.toString())) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 构建产品明细
     */
    private void buildProDetail(String materialCode) {
        /*
         * 是否填写基本信息
         */
        if (!verifyOrg()) {
            this.getView().showMessage(MarketBillMsgConstant.SELECT_STOCK_ORG);
            this.getModel().deleteEntryRow("yxgf_ent_prodeuct", 0);
            return;
        }

        Object cusType = this.getModel().getValue("yxgf_cus_type");
        if (cusType == null) {
            this.getView().showMessage(MarketBillMsgConstant.SELECT_CUS_TYPE);
            this.getModel().deleteEntryRow("yxgf_ent_prodeuct", 0);
            return;
        }

        /*
         * 添加产品信息
         */
        boolean isExist = false;
        DynamicObjectCollection collection = getModel().getEntryEntity(MarketBillIdConstant.PRODUCT_DETAIL);
        if (collection != null && collection.size() > 1) {
            for (DynamicObject entry : collection) {
                if (StringUtils.equals(materialCode, entry.get("yxgf_product_code").toString())) {
                    isExist = true;
                    break;
                }
            }
        }
        if (!isExist) {
            QFilter qfilter = new QFilter("number", QCP.equals, materialCode);
            DynamicObject dynObj = QueryServiceHelper.queryOne("bd_material", "id,number,name,modelnum", qfilter.toArray());
            int index = this.getModel().createNewEntryRow(MarketBillIdConstant.PRODUCT_DETAIL) - 1;
            getModel().setValue("yxgf_product_code", dynObj.get("number"), index);
            getModel().setValue("yxgf_product_name", dynObj.get("name"), index);
            getModel().setValue("yxgf_product_spec", dynObj.get("modelnum"), index);
        } else if (collection.size() > 1) {
            this.getModel().deleteEntryRow(MarketBillIdConstant.PRODUCT_DETAIL, collection.size() - 1);
        }
    }


    /**
     * 计算产品价格
     */
    public void calculateProPrice() {
        int proRow = getProRow(MarketBillIdConstant.PRODUCT_DETAIL);
        DynamicObjectCollection parProEntity = this.getModel().getEntryEntity("yxgf_ent_prodeuct");

        // 1、获取原料价格分录列表
        List<MarketFormulaPriceDto> priceList = getFormulaPriceDetail();

        // 2、获取基本费用
        BaseCostDto cost = getBaseCost();

        // 3、获取物料
        List<MarketProductDto> proList = getProFormula();
        // 获取产品
        for (MarketProductDto pro : proList) {
            if (pro != null && pro.getMatList().size() > 0) {
                // 获取配方
                List<MarketFormulaReq> matList = new ArrayList<>();
                for (MarketFormulaDto mat : pro.getMatList()) {
                    MarketFormulaReq req = new MarketFormulaReq();
                    req.setMatId(mat.getMatId());
                    req.setDosage(mat.getDosage());
                    req.setProportion(mat.getProportion());
                    matList.add(req);
                }

                // 4、计算产品价格
                CustomApiResult<MarketProductDto> apiResult = DispatchServiceHelper.invokeService(
                        "yxgf.oem.oemquotemgt.mservice.factory",
                        "llj-quotemgt", "IMarketBillService",
                        "calProPrice",
                        matList,priceList, cost);
                MarketProductDto data = apiResult.getData();

                // 5、渲染产品
                DynamicObject proObj = parProEntity.get(proRow);
                // DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("yxgf_ent_prodeuct");
                if (proObj != null) {
                    // 配方成本
                    this.getModel().setValue("yxgf_formula_amount", data.getForPrice(), proRow);
                    // 产品价格
                    this.getModel().setValue("yxgf_product_price", data.getProPrice(), proRow);
                    // 友商价
                    this.getModel().setValue("yxgf_competitor_price", data.getComPrice(), proRow);
                }
                // 更新产品view
                this.getView().updateView("yxgf_ent_prodeuct");
            }
        }
    }

    /**
     * 产品营养占比明细
     */
    public void selectNutItem() {
        // 获取原料
        List<MarketProductDto> proList = getProFormula();
        for (MarketProductDto pro : proList) {
            if (pro != null && pro.getMatList().size() > 0) {
                /*
                 *  1、计算原料占比
                 */
                List<MarketFormulaReq> reqList = new ArrayList<>();
                BigDecimal matTotal = new BigDecimal(0);
                // 获取原料
                for (MarketFormulaDto mat : pro.getMatList()) {
                    matTotal = matTotal.add(mat.getDosage());

                    MarketFormulaReq req = new MarketFormulaReq();
                    req.setMatId(mat.getMatId());
                    req.setDosage(mat.getDosage());
                    reqList.add(req);
                }
                // 使用量大于1000参与计算
                boolean result = matTotal.compareTo(new BigDecimal(NumConstant.DEF_DOSAGE)) < 0;
                if (result) {
                    getView().showSuccessNotification(MarketBillMsgConstant.SELECT_DOSAGE_NOT_ENOUGH);
                    return;
                }
                // 计算占比
                MarketBillServiceImpl marketBillService = new MarketBillServiceImpl();
                List<MarketFormulaDto> propList = marketBillService.calForProportion(reqList, matTotal);

                /*
                 * 2、更新占比
                 */
                int proRow = getProRow(MarketBillIdConstant.PRODUCT_DETAIL);
                DynamicObjectCollection parProEntity = this.getModel().getEntryEntity("yxgf_ent_prodeuct");

                // 子单据体
                // DynamicObjectCollection subMatEntity = parProEntity.get(proRow).getDynamicObjectCollection("yxgf_ent_product_formula");
                for (int i = 0; i < propList.size(); i++) {
                    MarketFormulaDto data = propList.get(i);
                    this.getModel().setValue("yxgf_material_code", data.getMatId(), i, proRow);
                    this.getModel().setValue("yxgf_use_num", data.getDosage(), i, proRow);
                    this.getModel().setValue("yxgf_mat_proportion", data.getProportion(), i, proRow);
                    this.getView().updateView("yxgf_ent_product_formula");
                }


                /*
                 * 3、获取营养项目数据
                 * (未添加营养项目-测试)
                 */
//                List<MarketProductDto> materialList = getProFormula();
//                CustomApiResult<List<MarketNutItemDto>> apiResult = DispatchServiceHelper.invokeService(
//                        "yxgf.oem.oemquotemgt.mservice.factory",
//                        "llj-quotemgt", "MarketBillServiceImpl",
//                        "getNutItemProportion",
//                        materialList);

//                List<MarketNutItemDto> itemList = apiResult.getData();
                List<MarketNutItemDto> itemList = null;

                // 更新营养项目
//                genNutItemEntity(proRow, itemList);
//                for (int i = 0; i < itemList.size(); i++) {
//                    MarketNutItemDto data = itemList.get(i);
//                    this.getModel().setValue("yxgf_item_name", data.getItemName(), i, proRow);
//                    this.getModel().setValue("yxgf_proportion", data.getProportion(), i, proRow);
//                    this.getView().updateView("yxgf_ent_prodeuct_nutr");
//                }
//
//
//                IEntryOperate entryOperate = this.getModel();
//                entryOperate.setEntryCurrentRowIndex(MarketBillIdConstant.PRODUCT_DETAIL, proRow);
//                for (int i = 0; i < itemList.size(); i++) {
//                    MarketNutItemDto item = itemList.get(i);
//
//                    entryOperate.createNewEntryRow("yxgf_ent_prodeuct_nutr");
//                    // this.getModel().setValue("fk_yxgf_material_item", item.getItemId(), i, parentRow);
//                    this.getModel().setValue("yxgf_item_name", item.getItemName(), i, proRow);
//                    this.getModel().setValue("fk_yxgf_proportion", item.getProportion(), i, proRow);
//                    this.getView().updateView("yxgf_ent_prodeuct_nutr");
//                }
            }
        }
    }


    /**
     * 根据单据体产品获取子配方信息
     *
     * @return
     */
    public List<MarketProductDto> getProFormula() {
        List<MarketProductDto> proDtoList = new ArrayList<>();

        DynamicObjectCollection masterEntity = getModel().getEntryEntity("yxgf_ent_prodeuct");
        if (masterEntity != null && masterEntity.size() > 0) {
            // 获取产品
            for (DynamicObject dynObj : masterEntity) {
                MarketProductDto marketProductDto = new MarketProductDto();
                marketProductDto.setProCode(dynObj.getString("yxgf_product_code"));
                // 获取配方
                List<MarketFormulaDto> formulaDtoList = new ArrayList<>();
                DynamicObjectCollection subEntity = dynObj.getDynamicObjectCollection("yxgf_ent_product_formula");
                for (int i = 0; i < subEntity.size(); i++) { // 物料对象
                    DynamicObject matDObj = (DynamicObject) subEntity.get(i).get("yxgf_material_code");
                    if (matDObj != null) {
                        MarketFormulaDto formulaDto = new MarketFormulaDto();
                        Long matNo = (Long) matDObj.get("id");
                        formulaDto.setMatId(matNo);
                        // 获取view值
                        BigDecimal dosage  = (BigDecimal) this.getModel().getValue("yxgf_use_num",i);
                        BigDecimal prop = (BigDecimal) this.getModel().getValue("yxgf_mat_proportion",i);
                        formulaDto.setProportion(prop);
                        formulaDto.setDosage(dosage);
                        formulaDtoList.add(formulaDto);
                    }
                }
                marketProductDto.setMatList(formulaDtoList);
                proDtoList.add(marketProductDto);
            }
        }
        return proDtoList;
    }

    /**
     * 获取原料价格
     *
     * @return
     */
    public List<MarketFormulaPriceDto> getFormulaPriceDetail() {
        List<MarketFormulaPriceDto> resList = new ArrayList<>();

        DynamicObjectCollection masterEntity = getModel().getEntryEntity(MarketBillIdConstant.MAT_PRICE_DETAIL);
        if (masterEntity != null && masterEntity.size() > 0) {
            for (DynamicObject entry : masterEntity) {
                DynamicObject priceDObj = (DynamicObject) entry.get("yxgf_material_no");
                if(priceDObj != null){
                    String matCode = (String) priceDObj.get("number");
                    Long matId = (Long) priceDObj.get("id");
                    BigDecimal priceing = (BigDecimal) entry.get("yxgf_pricing");
                    BigDecimal comPrice = (BigDecimal) entry.get("yxgf_comp_price");

                    MarketFormulaPriceDto tem = new MarketFormulaPriceDto();
                    tem.setMatCode(matCode);
                    tem.setMatId(matId);
                    tem.setPricing(priceing);
                    tem.setComPrice(comPrice);

                    resList.add(tem);
                }
            }
        }
        return resList;
    }

    private BaseCostDto getBaseCost() {
        BaseCostDto baseCostDto = new BaseCostDto();
        BigDecimal processCost = (BigDecimal) getModel().getValue("yxgf_process_amount");
        BigDecimal wastageCost = (BigDecimal) getModel().getValue("yxgf_per_consume");
        BigDecimal packCost = (BigDecimal) getModel().getValue("yxgf_pack_amount");
        BigDecimal deliCost = (BigDecimal) getModel().getValue("yxgf_del_amount");
        BigDecimal tmCost = (BigDecimal) getModel().getValue("yxgf_other_amount");

        baseCostDto.setProcessCost(processCost == null ? BigDecimal.ZERO : processCost);
        baseCostDto.setWastageCost(wastageCost == null ? BigDecimal.ZERO : wastageCost);
        baseCostDto.setPackCost(packCost == null ? BigDecimal.ZERO : packCost);
        baseCostDto.setDeliCost(deliCost == null ? BigDecimal.ZERO : deliCost);
        baseCostDto.setOtherCost(tmCost == null ? BigDecimal.ZERO : tmCost);
        return baseCostDto;
    }


    /**
     * 配方版本信息
     *
     * @param data
     */
    private List<MarketProductDto> getFormulaVersion(DynamicObject data) {
        Long billId = (Long) data.get("id");
        DynamicObject bill = BusinessDataServiceHelper.loadSingle(billId, "yxgf_formula_version");
        DynamicObjectCollection parProEntity = bill.getDynamicObjectCollection("entryentity");
        // 主数据
        List<MarketProductDto> productList = new ArrayList<>();
        if (parProEntity != null && parProEntity.size() > 0) {
            for (int i = 0; i < parProEntity.size(); i++) {
                String proCode = parProEntity.get(i).getString("yxgf_product_code");
                String proName = parProEntity.get(i).getString("yxgf_product_name");
                String proSpec = parProEntity.get(i).getString("yxgf_spec");

                MarketProductDto dt = new MarketProductDto();
                dt.setProCode(proCode);
                dt.setProName(proName);
                dt.setSpec(proSpec);

                // 子数据源
                DynamicObjectCollection subMatEntity = parProEntity.get(i).getDynamicObjectCollection("yxgf_subentryentity1");
                if (subMatEntity != null && subMatEntity.size() > 0) {
                    List<MarketFormulaDto> formulaDtoList = new ArrayList<>();
                    for (int j = 0; j < subMatEntity.size(); j++) {
                        DynamicObject matDbj = (DynamicObject) subMatEntity.get(j).get("yxgf_material_code");
                        String matNo = (String) matDbj.get("number");
                        Long matId = (Long) matDbj.get("id");
                        BigDecimal dosage = (BigDecimal) subMatEntity.get(j).get("yxgf_use_num");
                        BigDecimal prop = (BigDecimal) subMatEntity.get(j).get("yxgf_proportion");

                        MarketFormulaDto fDto = new MarketFormulaDto();
                        fDto.setMatId(matId);
                        fDto.setMatCode(matNo);
                        fDto.setDosage(dosage);
                        fDto.setProportion(prop);
                        formulaDtoList.add(fDto);
                    }
                    dt.setMatList(formulaDtoList);
                }
                productList.add(dt);
            }
        }
        return productList;
    }

    /**
     * 导入配方版本
     *
     * @param data
     */
    private void importFormulaVersion(DynamicObject data) {
        List<MarketProductDto> list = getFormulaVersion(data);
        genFormulaVersion(list);
    }

    /**
     * 导入实例化
     *
     * @param data
     */
    private void importFormulaInst(DynamicObject data) {
        // 获取实例化数据  yxgf_formula_instantiatio  - entryentity [yxgf_material_raws、yxgf_proportion_raw]


        // 获取实例化配方数据
        List<MarketProductDto> list = getFormulaVersion(data);
        genFormulaVersion(list);
    }

    /**
     * 生成配方主数据
     *
     * @param productList
     */
    private void genFormulaVersion(List<MarketProductDto> productList) {
        if (productList != null && productList.size() > 0) {
            for (int i = 0; i < productList.size(); i++) {
                MarketProductDto pro = productList.get(i);
                int mainRow = this.getModel().createNewEntryRow(MarketBillIdConstant.PRODUCT_DETAIL);
                this.getModel().setEntryCurrentRowIndex(MarketBillIdConstant.PRODUCT_DETAIL, mainRow);
                // 构建营销单产品
                getModel().setValue("yxgf_product_code", pro.getProCode(), mainRow);
                getModel().setValue("yxgf_product_name", pro.getProName(), mainRow);
                getModel().setValue("yxgf_product_spec", pro.getSpec(), mainRow);

                IEntryOperate entryOperate = this.getModel();
                entryOperate.setEntryCurrentRowIndex(MarketBillIdConstant.PRODUCT_DETAIL, mainRow);

                List<MarketFormulaDto> materialList = productList.get(i).getMatList();
                if (materialList != null && materialList.size() > 0) {
                    createSubEntity(i, -1, materialList);
                }
                this.getView().updateView(MarketBillIdConstant.PRODUCT_DETAIL);

            }
        }

    }

    /**
     * 添加子配方数据
     *
     * @param parentRow
     * @param subRow       -1:不自定子行号
     * @param materialList
     */
    private void createSubEntity(int parentRow, int subRow, List<MarketFormulaDto> materialList) {
        IEntryOperate entryOperate = this.getModel();
        entryOperate.setEntryCurrentRowIndex(MarketBillIdConstant.PRODUCT_DETAIL, parentRow);
        int parIndex = (parentRow == -1) ? 0 : parentRow;

        List<MarketFormulaPriceDto> matPriceList = new ArrayList<>();

        if (subRow == -1) {
            for (int i = 0; i < materialList.size(); i++) {
                entryOperate.createNewEntryRow("yxgf_ent_product_formula");
                this.getModel().setValue("yxgf_material_code", materialList.get(i).getMatId(), i, parIndex);
                this.getModel().setValue("yxgf_use_num", materialList.get(i).getDosage(), i, parIndex);
                this.getModel().setValue("yxgf_mat_proportion", materialList.get(i).getProportion(), i, parIndex);
                this.getView().updateView("yxgf_ent_product_formula");

                MarketFormulaPriceDto dto = new MarketFormulaPriceDto();
                dto.setMatId(materialList.get(i).getMatId());
            }
        } else {
            entryOperate.createNewEntryRow("yxgf_ent_product_formula");
            this.getModel().setValue("yxgf_material_code", materialList.get(0).getMatId(), subRow, parIndex);
            this.getModel().setValue("yxgf_use_num", BigDecimal.ZERO, subRow, parIndex);
            this.getModel().setValue("yxgf_mat_proportion", BigDecimal.ZERO, subRow, parIndex);
            this.getView().updateView("yxgf_ent_product_formula");

            MarketFormulaPriceDto dto = new MarketFormulaPriceDto();
            dto.setMatId(materialList.get(0).getMatId());
            matPriceList.add(dto);
        }
        // 更新价格明细
        bachUpdateFormulaPrice(matPriceList);
    }


    /**
     * 生成营养项目
     *
     * @param parentRow
     * @param itemDtoList
     */

    private void genNutItemEntity(int parentRow, List<MarketNutItemDto> itemDtoList) {
        IEntryOperate entryOperate = this.getModel();
        entryOperate.setEntryCurrentRowIndex(MarketBillIdConstant.PRODUCT_DETAIL, parentRow);
        for (int i = 0; i < itemDtoList.size(); i++) {
            MarketNutItemDto item = itemDtoList.get(i);

            entryOperate.createNewEntryRow("yxgf_ent_prodeuct_nutr");
            // this.getModel().setValue("fk_yxgf_material_item", item.getItemId(), i, parentRow);
            this.getModel().setValue("yxgf_item_name", item.getItemName(), i, parentRow);
            this.getModel().setValue("fk_yxgf_proportion", item.getProportion(), i, parentRow);
            this.getView().updateView("yxgf_ent_prodeuct_nutr");
        }
    }

    /**
     * 批量更新配方价格
     *
     * @param materialList
     */
    private void bachUpdateFormulaPrice(List<MarketFormulaPriceDto> materialList) {
        List<MarketFormulaPriceDto> resList = new ArrayList<>();
        for (MarketFormulaPriceDto tem : materialList) {
            MarketFormulaPriceDto dto = new MarketFormulaPriceDto();
            dto.setMatId(tem.getMatId());

            // 获取价格

            // 生成价格集合
            resList.add(dto);
        }

        // 更新价格
    }


    /**
     * 设置客户
     * yxgf_crm_customer
     * yxgf_his_customer
     */
    private void setDefCusType() {
        Object cusType = this.getModel().getValue("yxgf_cus_type");
        if (cusType == null && StringUtils.equals(cusType.toString(), "0")) {
            getModel().setValue(MarketBillIdConstant.MARKET_CUS_TYPE, CusTypeEnum.MARKET_CUS_FIST.getCode());
            // 隐藏 yxgf_his_customer
            this.getView().setVisible(true, "yxgf_crm_customer");
            this.getView().setVisible(false, "yxgf_his_customer");
        } else {
            getModel().setValue(MarketBillIdConstant.MARKET_CUS_TYPE, CusTypeEnum.MARKET_SEC_HIS.getCode());
            this.getView().setVisible(true, "yxgf_his_customer");
            this.getView().setVisible(false, "yxgf_crm_customer");
        }
    }
}